<template>
  <div v-if="giveRule" class="dialog-give-vip">
    <el-dialog
      title="赠送会员"
      :visible.sync="dialogVisible"
      width="750px"
      :close-on-click-modal="false"
      @open="handleDialogOpen('form')"
      @close="close"
    >
      <div v-loading="loading" class="form" element-loading-text="生成中">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item prop="categoryId" label="卡类型：">
            <el-radio-group v-model="form.categoryId" size="medium">
              <el-radio
                v-for="item in cardList"
                :key="item.id"
                :label="item.id"
                :disabled="!item.status"
                border
              >{{ item.status?item.categoryName:item.categoryName+"(已停用)" }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 附赠余额 -->
          <el-form-item prop="extraBalance" label="附赠余额">
            <ul v-if="giveRule.defaultAmount.length>0" class="balance-btn clearfix">
              <li
                v-for="(item,index) in giveRule.defaultAmount"
                :key="index"
                :class="balanceIndex===index?'is-checked app-text-color-primary app-border-color-primary':'not-checked'"
                @click="changeBalance(index,item)"
              >{{ item/100 }}元</li>
            </ul>
            <el-input v-model="form.extraBalance" placeholder="请输入附赠金额" maxlength="10">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <!-- 祝福语 -->
          <el-form-item prop="blessing" label="祝语">
            <ul class="wish-btn clearfix">
              <li
                v-for="(item,index) in wishList"
                :key="index"
                :class="wistIndex===index?'is-checked app-text-color-primary app-border-color-primary':'not-checked'"
                @click="changeWishes(index,item.val)"
              >{{ item.name }}</li>
            </ul>
            <el-input
              v-model="form.blessing"
              type="textarea"
              placeholder="请输入祝语"
              :autosize="{ minRows: 2, maxRows: 10}"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round type="primary" @click="handleSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { setGiveVipCardRecord, getAllVipCardList } from '@/api/vip'
import { validateMoney, validateStrLen } from '@/utils/validate.js'
export default {
  props: {
    giveRule: {
      type: Object,
      require: true
    }
  },
  data() {
    /**
       * 表单校验方法相关
       */
    const validateRmb = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(`请输入附赠余额，无附赠则输入0`))
      } else if (!validateMoney(value, true)) {
        callback(new Error('请输入0或正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }
    const validateBlessing = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入祝福语'))
      } else if (!validateStrLen(value, 80)) {
        callback(new Error('长度不超过40个汉字或80个字符'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        categoryId: [
          {
            required: true,
            message: '请选中赠送卡类型',
            trigger: ['blur', 'change']
          }
        ],
        extraBalance: [
          {
            required: true,
            validator: validateRmb,
            trigger: ['blur', 'change']
          }
        ],
        blessing: [
          {
            required: true,
            validator: validateBlessing,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      wishList: [
        {
          id: 1,
          name: '默认',
          val: '如果生活给了你一个柠檬，不妨把它做成柠檬水'
        },
        {
          id: 2,
          name: '送好友',
          val: '不管未来有多遥远，路上一起欣赏风景的有你也有我'
        },
        {
          id: 3,
          name: '送爱人',
          val: '从前的日色变得慢，车马邮件都慢，一生只够爱一个人'
        },
        {
          id: 4,
          name: '送亲人',
          val:
              '种一棵树，总是需要付出无限的心血培养，还有花去一生的时间惦念，今日是否晴天'
        }
      ],
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      balanceIndex: null, // 赠送余额激活index
      wistIndex: 0, // 祝福语激活index
      cardList: null, // 卡列表
      cardIndex: null, // 当前激活的卡index
      code: null, //  赠送二维码code
      form: {
        giverId: '',
        categoryId: '',
        extraBalance: '',
        blessing: '如果生活给了你一个柠檬，不妨把它做成柠檬水'
      }
    }
  },
  mounted() {},
  methods: {
    // 获取会员卡列表
    getCardList() {
      getAllVipCardList().then(res => {
        this.cardList = res.data
      })
    },

    open() {
      this.show()
      this.getCardList()
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.$refs.form.resetFields()
      this.wistIndex = 0
      this.balanceIndex = null
      this.cardIndex = null
    },

    hide() {
      this.dialogVisible = false
    },

    /**
       *  按钮组
       */
    // 提交
    handleSubmit(formName) {
      const _this = this
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true
          const data = Object.assign({}, this.form)
          data.giverId = this.$store.state.user.id
          data.extraBalance = this.$math.mul(data.extraBalance, 100, 0)
          setGiveVipCardRecord(data)
            .then(res => {
              this.$emit('refreshGiveRecord')
              //  打开详情
              this.code = res.data
              this.openGiveDetail()
              this.loading = false
              this.hide()
            })
            .catch(err => {
              this.loading = false
            })
        }
      })
    },

    // 切换可赠送余额
    changeBalance(index, val) {
      this.balanceIndex = index
      this.form.extraBalance = val / 100
    },

    // 切换祝语
    changeWishes(index, val) {
      this.wistIndex = index
      this.form.blessing = val
    },

    // 查看详情
    openGiveDetail() {
      this.$emit('openGiveDetail', this.code)
    },

    // 验证
    handleDialogOpen(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate()
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .dialog-give-vip {
    .form {
      .el-radio + .el-radio {
        margin-left: 0;
      }
      .el-radio {
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }

    /* 余额按钮 */
    .balance-btn {
      li {
        float: left;
        padding: 10px;
        margin-right: 20px;
        margin-bottom: 10px;
        border-radius: 4px;
        line-height: 1;
        text-align: center;
        cursor: pointer;
      }
    }

    /* 祝福按钮 */
    .wish-btn {
      li {
        float: left;
        width: 80px;
        padding: 10px;
        margin-right: 20px;
        margin-bottom: 10px;
        border-radius: 4px;
        line-height: 1;
        text-align: center;
        cursor: pointer;
      }
    }

    /* 是否选择 */
    .is-checked {
      border-width: 1px;
      border-style: solid;
    }
    .not-checked {
      border: 1px solid #e7e7e7;
    }
  }
</style>
